<template>
  <div class="app-container">
    <el-form class="formList" :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch"
      label-width="80px">
      <el-row>

          <el-form-item label="论文分类" prop="groupUid">
            <el-select v-model="queryParams.groupUid"
              placeholder="请选择类别"
              clearable>
              <el-option v-for="group in queryGroups"
                :key="group.groupUid"
                :label="group.groupName"
                :value="group.groupUid" />
            </el-select>
          </el-form-item>
          <el-form-item label="折扣名称" prop="unitName">
            <el-input v-model="queryParams.unitName" placeholder="请输入折扣名称" clearable size="small"
              @keyup.enter.native="handleQuery" />
          </el-form-item>

          <el-form-item label="数据状态" prop="dataStatus">
            <el-select v-model="queryParams.dataStatus" placeholder="请选择状态" clearable size="small">
              <el-option v-for="dict in statusOptions" :key="dict.dictValue" :label="dict.dictLabel"
                :value="dict.dictValue" />
            </el-select>
          </el-form-item>

          <el-form-item style="margin-left: 22px;">
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>

      </el-row>
    </el-form>

    <el-row class="row-mbinfo" style="margin-left: 0px; margin-right: 0px;">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['product:unit:add']">新增</el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <div class="divTable">
      <el-table border v-loading="loading" :data="unitList" @selection-change="handleSelectionChange">
        <el-table-column label="论文分类" align="center" prop="groupName" />
        <el-table-column label="折扣名称" align="center" prop="unitName" />
        <el-table-column label="开始下载量" align="center" prop="startCount" />
        <el-table-column label="结束下载量" align="center" prop="endCount" />
        <el-table-column label="折扣" align="center" prop="discount" />
        <el-table-column label="数据状态" align="center" prop="dataStatus">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.dataStatus" active-value="1" inactive-value="0"
              @change="handleStatusChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="排序" align="center" prop="dataPriority"  />

        <el-table-column label="更新时间" align="center" prop="updateTime" width="180" >
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
              v-hasPermi="['product:unit:edit']">修改</el-button>
            <el-button v-if="scope.row.dataStatus == '0' " size="mini" type="text" icon="el-icon-delete"
              @click="handleDelete(scope.row)" v-hasPermi="['product:unit:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </div>


    <!-- 添加或修改商品单位对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body @keyup.enter.native="submitForm">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="论文类别"
          prop="groupUid">
          <el-select v-model="form.groupUid"
            placeholder="请选择类别"
            clearable>
            <el-option v-for="group in lunwenGroups"
              :key="group.groupUid"
              :label="group.groupName"
              :value="group.groupUid" />
          </el-select>
        </el-form-item>
        <el-form-item label="折扣名称" prop="unitName">
          <el-input v-model="form.unitName" placeholder="请输入折扣名称" class="select-normal" maxlength="20"
             />
        </el-form-item>
        <el-form-item label="开始下载量" prop="startCount">
          <el-input v-model="form.startCount" placeholder="请输入开始下载量" class="select-normal" maxlength="10" min="0" />
        </el-form-item>
        <el-form-item label="结束下载量" prop="endCount">
          <el-input v-model="form.endCount" placeholder="请输入结束下载量" class="select-normal" maxlength="10" min="0"/>
        </el-form-item>
        <el-form-item label="折扣" prop="discount">
          <el-input v-model="form.discount" placeholder="请输入折扣" class="select-normal" maxlength="10" max="1" min="0.1" /> <span>&nbsp;例如：8折输入0.8,不打折输入1</span>
        </el-form-item>
        <el-form-item label="数据状态">
          <el-radio-group v-model="form.dataStatus">
            <el-radio label="1">有效</el-radio>
            <el-radio label="0">无效</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序" prop="dataPriority">
          <el-input-number v-model="form.dataPriority" placeholder="请输入排序" controls-position="right" :min="0"
            class="select-normal" :max="999999" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import {
    listUnit,
    getUnit,
    delUnit,
    addUnit,
    updateUnit,
    updateUnitStatus
  } from "@/api/product/unit";

  import {
    productUnitUse
  } from "@/api/product/info"
  import {
    firstGroupList,
  } from "@/api/product/group";

  export default {
    name: "Unit",
    components: {},
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        //选中数组的名字
        names: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 商品单位表格数据
        unitList: [],
        // 弹出层标题
        title: "",
        //查看详细标题
        viewTitle: "",
        // 是否显示弹出层
        open: false,
        //是否显示查看详细弹出层
        viewOpen: false,
        //常用状态数据字典
        statusOptions: [],
        //查看详细数据
        showData: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          unitName: null,
          groupUid: null,
          dataStatus: null,
        },
        lunwenGroups: [],
        queryGroups: [],
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          groupUid: [{
            required: true,
            message: "请选择论文分类",
            trigger: "blur"
          }],
          unitName: [{
            required: true,
            message: "折扣名称不能为空",
            trigger: "blur"
          }],
          startCount: [{
            required: true,
            message: "开始下载量不能为空",
            trigger: "blur"
          }],
          endCount: [{
            required: true,
            message: "结束下载量不能为空",
            trigger: "blur"
          }],
          discount: [{
            required: true,
            message: "折扣不能为空",
            trigger: "blur"
          }],
          dataPriority: [{
            required: true,
            message: "排序不能为空",
            trigger: "blur"
          }]
        }
      };
    },
    created() {
      this.getList();
      this.getDicts("sys_data_status").then(response => {
        this.statusOptions = response.data;
      });
      firstGroupList().then(respone => {
        this.lunwenGroups = respone.data;
        this.queryGroups = respone.data;
      });
    },
    methods: {
      /** 查询商品单位列表 */
      getList() {
        this.loading = true;
        listUnit(this.queryParams).then(response => {
          this.unitList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },

      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          unitUid: null,
          unitName: null,
          dataStatus: "1",
          dataPriority: 10,
          createUid: null,
          createTime: null,
          updateUid: null,
          updateTime: null,
          platformUid: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.unitUid)
        this.names = selection.map(item => item.unitName)
        this.single = selection.length !== 1
        this.multiple = !selection.length
        //用于禁用删除
        if (this.multiple == false) {
          for (var i = 0; i < selection.length; i++) {
            var element = selection[i];
            if ("1" === element.dataStatus) {
              this.multiple = true;
              break;
            }
          }
        }
      },
      // 状态修改
      handleStatusChange(row) {
        let text = row.dataStatus === "0" ? "无效" : "有效";
        // 判断该单位是否被使用
        if (text == "无效") {
          this.pf(row, text);
        }else{
           updateUnitStatus(row.unitUid, row.dataStatus);
        }

      },
      pf(row, text) {
        console.log("1")
        this.$confirm('确定要把折扣名称为"' + row.unitName + '"设为' + text + '吗？', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          console.log(row.dataStatus);
          return updateUnitStatus(row.unitUid, row.dataStatus);
        }).then(() => {
          this.msgSuccess("操作成功");
          this.getList();
        }).catch(function() {
          row.dataStatus = row.dataStatus === "0" ? "1" : "0";
        });
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加折扣";
      },

      handCloseDetail() {
        this.viewOpen = false
        this.showData = []
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const unitUid = row.unitUid || this.ids
        getUnit(unitUid).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改折扣";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.unitUid != null) {
              updateUnit(this.form).then(response => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addUnit(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const unitUids = row.unitUid || this.ids;
        const names = row.unitName || this.names;
        this.$confirm('是否确认删除折扣单位名称为"' + names + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delUnit(unitUids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('product/unit/export', {
          ...this.queryParams
        }, `product_unit.xlsx`)
      }
    }
  };
</script>
